<template>
  <div class="add">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <a href="/hello">首页</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 进度条 -->
      <el-alert title="添加商品信息" :closable="false" show-icon center type="info" effect="dark"></el-alert>
      <el-steps align-center :active="activeName*1" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs切换栏 -->
      <el-form
        ref="addForm"
        label-position="top"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-tabs
          @tab-click="tabClick"
          tab-position="left"
          :before-leave="beforeLeave"
          v-model="activeName"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="goodsCateList"
                :props="goodsProps"
                :show-all-levels="false"
                v-model="addForm.goods_cat"
                @change="handleCateChange"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-checkbox-group
              v-for="item in checkList"
              :key="item.attr_id"
              v-model="item.attr_vals"
            >
              <el-form-item :label="item.attr_name">
                <el-checkbox border v-for="(cd,i) in item.attr_vals" :key="i" :label="cd"></el-checkbox>
              </el-form-item>
            </el-checkbox-group>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParamsList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- activeURL 图片上传地址 -->
            <!-- headers 请求头 -->
            <el-upload
              class="upload-demo"
              :action="activeURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handelSuccess"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addBtn" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 上传图片 查看 -->
    <el-dialog title="图片预览" :visible.sync="uploadDialogVisible" width="50%">
      <img :src="imgUploadUrl" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import { GetGoodsSort, TabClick, PostAddImages } from '@/api/api.js'
export default {
  name: 'BackShopAdd',

  data () {
    return {
      // 默认被选中的tabs
      activeName: '0',
      // 商品信息
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 被选中的属性值
        goods_cat: [],
        // 图片上传成功列表
        pics: [],
        // 富文本编辑
        goods_introduce: '',
        attrs: []
      },
      // 表单校验
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
      },
      // 分类下拉属性
      goodsProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品分类
      goodsCateList: [],
      // 动态参数列表
      checkList: [],
      // 静态参数列表
      onlyParamsList: [],
      // 图片上传地址
      activeURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传请求头
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览Show
      uploadDialogVisible: false,
      // 图片预览地址
      imgUploadUrl: ''
    };
  },

  created () {
    // 请求商品分类
    this.getCateList()
  },

  methods: {
    // 请求商品分类
    async getCateList () {
      const { data: res } = await GetGoodsSort()
      if (res.meta.status !== 200) return this.$message.error('请求分类失败')
      this.goodsCateList = res.data
    },
    // 处理下拉三级权限
    handleCateChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.info('请求三级分类')
        this.addForm.goods_cat = [];
      }
    },
    //切换之前的钩子函数
    beforeLeave (news, olds) {
      if (this.addForm.goods_cat.length !== 3 && olds === '0') {
        this.$message.error('请先获取商品分类信息')
        return false
      }
    },
    // 被选中时候出发
    async tabClick () {
      switch (this.activeName) {
        case '1':
          const { data: res } = await TabClick(this.cateId, {
            sel: 'many'
          })
          if (res.meta.status !== 200) return this.$message.error('请求参数失败')
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          })
          this.checkList = res.data;
          break;
        case '2':
          // 请求静态参数
          const { data: resT } = await TabClick(this.cateId, {
            sel: 'only'
          })
          if (resT.meta.status !== 200) return this.$message.error('请求静态参数失败')
          this.onlyParamsList = resT.data
          break
        default:
          break;
      }
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (file) {
      // 显示图片预览
      this.uploadDialogVisible = true;
      // 图片预览地址
      this.imgUploadUrl = file.response.data.url
    },
    // 文件列表移除文件时的钩子
    handleRemove (file) {
      const path = file.response.data.tmp_path;
      console.log(path);
      // 判断索引值删除当前元素
      const i = this.addForm.pics.findIndex(x => x === path)
      this.addForm.pics.splice(i, 1)
    },
    // 上传成功数组列表
    handelSuccess (response) {
      const url = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(url)
    },
    // 上传所有属性合集
    addBtn () {
      this.$refs.addForm.validate(async validate => {
        if (!validate) return this.$message.error('表单尚未补全！')
        if (this.checkList.length == 0) return this.$message.error('请按照后顺序排序执行')
        if (this.onlyParamsList.length == 0) return this.$message.error('请按照后顺序排序执行')
        // 表单预检验和先后顺序之后

        const form = _.cloneDeep(this.addForm);
        // 处理goods_cat数组
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.checkList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态参数
        this.onlyParamsList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // 发起网络请求
        const { data: res } = await PostAddImages(form)
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加成功!')
        // 跳转
        this.$router.push('/goods')
      })

    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0px;
}
.el-cascader {
  width: 100%;
}
.el-checkbox {
  margin: 0px 5px 0px 0px !important;
}
// 富文本css
.addBtn {
  margin: 15px;
}
</style>